package com.kakame.codenews.front.user.dao;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Repository;

import com.kakame.codenews.base.constant.DbTableConstant;
import com.kakame.codenews.base.constant.SystemConstant;
import com.kakame.codenews.base.util.DateUtil;
import com.kakame.codenews.base.util.EncryptUtil;
import com.kakame.codenews.base.util.SystemUtil;
import com.kakame.codenews.base.web.dao.JdbcBaseDao;
import com.kakame.codenews.base.web.fast.mapping.common.User;

@Repository
public class FrontUserDao extends JdbcBaseDao {

    /**
     * <pre>
     * <b>desc:</b> 根据用户名和密码查找对应用户，这里的用户名可以是邮箱或者账号  
     * <b>auth:</b> 何家明
     * <b>date:</b> 2018年6月6日 上午10:58:18
     * </pre>
     * @param userName
     * @return
     */
    public User findByUserAccountOrEmail(String userName) {
        String selectSql = "";
        selectSql += "SELECT ";
        selectSql += SystemUtil.convertArrayToString((DbTableConstant.T_COMMON_USER_COLUMNS));
        selectSql += "  FROM t_common_user ";
        selectSql += " WHERE status = 'C' AND (user_account = :userAccount OR user_email = :userEmail) ";
        Map<String, Object> paramMap = SystemUtil.getSOHashMap();
        paramMap.put("userAccount", userName);
        paramMap.put("userEmail", userName);
        List<User> list = list(selectSql, paramMap, User.class);
        if(list.size() == 1) {
            return list.get(0);
        }
        return null;  // wft??
    }
    
    /**
     * <pre>
     * <b>desc:</b> 用户注册 
     * <b>auth:</b> 何家明
     * <b>date:</b> 2018年6月6日 上午9:52:05
     * </pre>
     * @param userName
     * @param userPwd
     * @return
     */
    public int register(String userName, String userPwd) {
        String selectSql = "";
        selectSql += "SELECT id, user_name, user_account, user_pwd, user_salt, user_birth, user_gender, user_email, user_phone, user_exp, user_vip, user_money, user_large_icon, user_small_icon, user_status, create_time, create_user_id, update_time, update_user_id, status ";
        selectSql += "  FROM t_common_user ";
        selectSql += " WHERE status = 'C' AND user_account = :userAccount";
        Map<String, Object> selectMap = SystemUtil.getSOHashMap();
        selectMap.put("userAccount", userName);
        List<User> existList = list(selectSql, selectMap, User.class);
        if(existList.size() > 0) {
            return -1;
        }
        
        String insertSql = "";
        insertSql += "INSERT INTO t_common_user ";
        insertSql += "(id, user_name, user_account, user_pwd, user_salt, user_exp, user_vip, user_money, user_status, create_time, create_user_id, status) ";
        insertSql += "VALUES ";
        insertSql += "(:id, :userName, :userAccount, :userPwd, :userSalt, 0, 0, 0, 'C', now(), :createUserId, 'C') ";
        Date now = DateUtil.getNow();
        String salt = EncryptUtil.salt();
        String userId = SystemConstant.T_COMMON_USER + DateFormatUtils.format(now, "yyyyMMddHHmmssSSS");
        User user = User.create()
                        .id(userId)
                        .userName(userName)
                        .userAccount(userName)
                        .userPwd(EncryptUtil.encrypt(userPwd, salt))
                        .userSalt(salt)
                        .createUserId(userId)
                        .build();
        int rows = update(insertSql, user);
        return rows;
    }

	public User getById(String userId) {
		String selectSql = "";
        selectSql += "SELECT ";
        selectSql += SystemUtil.convertArrayToString((DbTableConstant.T_COMMON_USER_COLUMNS));
        selectSql += "  FROM t_common_user ";
        selectSql += " WHERE id = :userId ";
        Map<String, Object> paramMap = SystemUtil.getSOHashMap();
        paramMap.put("userId", userId);
        List<User> list = list(selectSql, paramMap, User.class);
        if(list.size() == 1) {
            return list.get(0);
        }
        return null;  // wft??
	}

    public int update(User user) {
        String updateSql = "";
        updateSql += "UPDATE t_common_user ";
        updateSql += "   SET user_name   = :userName, ";
        if(user.getUserBirth() != null) {
        	updateSql += "   user_birth  = :userBirth, ";
        }
        if(user.getUserGender() != null) {
        	updateSql += "   user_gender = :userGender, ";
        }
        updateSql += "       update_time = now(), ";
        updateSql += "       update_user_id = :updateUserId ";
        updateSql += " WHERE id = :id ";
        int rows = update(updateSql, user);
        return rows;
    }

    public User get(User user) {
        String selectSql = "";
        selectSql += "SELECT ";
        selectSql += SystemUtil.convertArrayToString((DbTableConstant.T_COMMON_USER_COLUMNS));
        selectSql += "  FROM t_common_user ";
        selectSql += " WHERE 1 = 1 ";
        if(StringUtils.isNotBlank(user.getUserAccount())) {
            selectSql += "AND user_account = :userAccount ";
        }
        if(StringUtils.isNotBlank(user.getUserPwd())) {
            selectSql += "AND user_pwd = :userPwd ";
        }
//        if(selectSql.endsWith(", ")) {
//            selectSql = selectSql.substring(0, selectSql.length() - 2);
//        }
        List<User> list = list(selectSql, user);
        if(list.size() == 1) {
            return list.get(0);
        }
        return null;  // wft??
    }
}
